package com.asman.vr

import android.R
import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.widget.FrameLayout
import com.asman.base.lib.utils.StatusBarUtil


/**
 * @author ybk
 * @date :2020/4/2 9:30 AM
 * @desc:
 */
/**
 * 解决webView键盘遮挡问题的类
 * Created by zqy on 2016/11/14.
 */
class KeyBoardListener(private val activity: Activity) {
    private var mChildOfContent: View? = null
    private var usableHeightPrevious = 0
    private var frameLayoutParams: FrameLayout.LayoutParams? = null

    fun init1() {
        val content = activity.findViewById<View>(R.id.content) as FrameLayout
        mChildOfContent = content.getChildAt(0)
        mChildOfContent!!.viewTreeObserver.addOnGlobalLayoutListener { possiblyResizeChildOfContent() }
        frameLayoutParams = mChildOfContent!!.layoutParams as FrameLayout.LayoutParams
    }

    private fun possiblyResizeChildOfContent() {
        //这里屏幕可用空间需要加上状态栏的高度
        val usableHeightNow = computeUsableHeight() + StatusBarUtil.getStatusBarHeight(activity)
        if (usableHeightNow != usableHeightPrevious) {
            val usableHeightSansKeyboard = mChildOfContent!!.rootView.height
            val heightDifference = usableHeightSansKeyboard - usableHeightNow
            if (heightDifference > usableHeightSansKeyboard / 4) {
                frameLayoutParams!!.height = (usableHeightSansKeyboard - heightDifference)
            } else {
                frameLayoutParams!!.height = usableHeightSansKeyboard
            }
            mChildOfContent!!.requestLayout()
            usableHeightPrevious = usableHeightNow
        }
    }

    private fun computeUsableHeight(): Int {
        val r = Rect()
        mChildOfContent!!.getWindowVisibleDisplayFrame(r)
        return r.bottom - r.top
    }

    companion object {
        private var keyBoardListener: KeyBoardListener? = null
        fun getInstance(activity: Activity): KeyBoardListener {
            keyBoardListener = KeyBoardListener(activity)
            return keyBoardListener!!
        }
    }

}